package com.dldata.devtools30.cfg;


import com.dldata.devtools30.businessmodel.QueryResult;
import com.dldata.devtools30.common.EnumUtils;
import com.dldata.devtools30.entity.DevtModelMetadataFieldEntity;
import com.dldata.devtools30.entity.DevtModelMetadataTableEntity;
import com.dldata.devtools30.repository.common.CommonApiDao;
import com.dldata.devtools30.repository.common.DlBaseJdbcTemplate;
import com.dldata.devtools30.service.metadata.DevtModelMetadataFieldService;
import com.dldata.devtools30.service.metadata.DevtModelMetadataTableService;
import com.dldata.devtools30.service.metadata.DevtModelMetadataTypeService;
import com.dldata.devtools30.utils.DBTypeUtil;
import com.dldata.devtools30.utils.Result;
import com.dldata.devtools30.utils.dbtable.DbTableManager;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerApplicationContext;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Slf4j
@Component
public class ModelTableViewCreateTask {
    @Autowired
    private  WebServerApplicationContext applicationContext;
    @Autowired
    private  DevtModelMetadataTableService metadataTableService;
    
    @Autowired
    private  DevtModelMetadataFieldService metadataFieldService;
    
    @Autowired
    private  DevtModelMetadataTypeService metadataTypeService;
    
    @Autowired
    private  DlBaseJdbcTemplate dlBaseJdbcTemplate;

    public void createModelTableView(){
        CommonApiDao commonApiDao = applicationContext.getBean(CommonApiDao.class);
        List<DevtModelMetadataTableEntity> metadataTableEntityList = commonApiDao.getScrollData(DevtModelMetadataTableEntity.class).getResultlist();
        for (Iterator<DevtModelMetadataTableEntity> iterator = metadataTableEntityList.iterator(); iterator.hasNext(); ) {
            DevtModelMetadataTableEntity metadataTableEntity =  iterator.next();
            dbSyncInter(metadataTableEntity);
        }
    }
    
    public void dbSyncInter(DevtModelMetadataTableEntity metadataTableEntity){
        try {
            if(metadataTableEntity.getStoretype().equals(EnumUtils.StoreTypeEnum.普通.name())){
                List<DevtModelMetadataFieldEntity> metadataFieldEntities=metadataFieldService.getAllByTid(metadataTableEntity.getId());
                DBTypeUtil.DBTYPE dbtype=DBTypeUtil.getDbtype(dlBaseJdbcTemplate.getDataSource());
                DbTableManager dbTableManager = new DbTableManager(dlBaseJdbcTemplate,dbtype);
                String updatetablesql = dbTableManager.dbsyncTableSql(metadataTableEntity, metadataFieldEntities);
                
                StringBuilder dropviewSql = new StringBuilder();
                dropviewSql.append("\r\n");
                dropviewSql.append(" IF EXISTS(SELECT 1 FROM sys.views WHERE name='"+metadataTableEntity.getViewcode()+"') ");
                dropviewSql.append(" DROP VIEW "+metadataTableEntity.getViewcode()+"; ");
                dropviewSql.append(" \r\n\r\n  ");
                
                StringBuilder createview = new StringBuilder();
                createview.append(" create view "+metadataTableEntity.getViewcode());
                createview.append(" \r\nas ");
                createview.append(" \r\nselect * ");
                createview.append(" \r\nfrom ").append(metadataTableEntity.getCode()).append(" with(nolock) ");
                
                dlBaseJdbcTemplate.update(updatetablesql.toString());
                dlBaseJdbcTemplate.update(dropviewSql.toString());
                dlBaseJdbcTemplate.update(createview.toString());
            }
            
            if(metadataTableEntity.getStoretype().equals(EnumUtils.StoreTypeEnum.json.name())){
                DBTypeUtil.DBTYPE dbtype=DBTypeUtil.getDbtype(dlBaseJdbcTemplate.getDataSource());
                DbTableManager dbTableManager = new DbTableManager(dlBaseJdbcTemplate,dbtype);
                List<DevtModelMetadataFieldEntity> metadataFieldEntities=new ArrayList<>();
                DevtModelMetadataFieldEntity sysModelMetadataFieldEntity=new DevtModelMetadataFieldEntity();
                sysModelMetadataFieldEntity.setFieldType(DbTableManager.FIELDTYPE.STRING.getCode());
                sysModelMetadataFieldEntity.setFieldCode("jsondata");
                sysModelMetadataFieldEntity.setTypeLength(Integer.MAX_VALUE);
                metadataFieldEntities.add(sysModelMetadataFieldEntity);
                
                sysModelMetadataFieldEntity=new DevtModelMetadataFieldEntity();
                sysModelMetadataFieldEntity.setFieldType(DbTableManager.FIELDTYPE.STRING.getCode());
                sysModelMetadataFieldEntity.setFieldCode("id");
                sysModelMetadataFieldEntity.setTypeLength(64);
                sysModelMetadataFieldEntity.setPkey(1);
                sysModelMetadataFieldEntity.setBz("id");
                metadataFieldEntities.add(sysModelMetadataFieldEntity);
                
                sysModelMetadataFieldEntity=new DevtModelMetadataFieldEntity();
                sysModelMetadataFieldEntity.setFieldType(DbTableManager.FIELDTYPE.STRING.getCode());
                sysModelMetadataFieldEntity.setFieldCode("_usercode");
                sysModelMetadataFieldEntity.setTypeLength(256);
                sysModelMetadataFieldEntity.setBz("用户编码");
                metadataFieldEntities.add(sysModelMetadataFieldEntity);
                
                sysModelMetadataFieldEntity=new DevtModelMetadataFieldEntity();
                sysModelMetadataFieldEntity.setFieldType(DbTableManager.FIELDTYPE.DATETIME.getCode());
                sysModelMetadataFieldEntity.setFieldCode("_createtime");
                sysModelMetadataFieldEntity.setTypeLength(64);
                sysModelMetadataFieldEntity.setBz("创建时间");
                metadataFieldEntities.add(sysModelMetadataFieldEntity);
                
                sysModelMetadataFieldEntity=new DevtModelMetadataFieldEntity();
                sysModelMetadataFieldEntity.setFieldType(DbTableManager.FIELDTYPE.DATETIME.getCode());
                sysModelMetadataFieldEntity.setFieldCode("_updatetime");
                sysModelMetadataFieldEntity.setTypeLength(64);
                sysModelMetadataFieldEntity.setBz("更新时间");
                metadataFieldEntities.add(sysModelMetadataFieldEntity);
                
                sysModelMetadataFieldEntity=new DevtModelMetadataFieldEntity();
                sysModelMetadataFieldEntity.setFieldType(DbTableManager.FIELDTYPE.DATETIME.getCode());
                sysModelMetadataFieldEntity.setFieldCode("_datatime");
                sysModelMetadataFieldEntity.setTypeLength(64);
                sysModelMetadataFieldEntity.setBz("更新时间");
                metadataFieldEntities.add(sysModelMetadataFieldEntity);
                
  
                String updatetablesql = dbTableManager.dbsyncTableSql(metadataTableEntity, metadataFieldEntities);
     
                StringBuilder dropviewSql=new StringBuilder();
                dropviewSql.append(" IF EXISTS(SELECT 1 FROM sys.views WHERE name='"+metadataTableEntity.getViewcode()+"') ");
                dropviewSql.append(" DROP VIEW "+metadataTableEntity.getViewcode()+"; ");
                dropviewSql.append(" \r\n\r\n  ");
                StringBuilder createview = new StringBuilder();
                createview.append(" create view "+metadataTableEntity.getViewcode());
                createview.append(" \r\nas ");
                createview.append(" \r\nselect _datatime _datatime , ");
                List<DevtModelMetadataFieldEntity> metadataFieldEntitiereal=metadataFieldService.getAllByTid(metadataTableEntity.getId());
                for (int i = 0; i < metadataFieldEntitiereal.size(); i++) {
                    DevtModelMetadataFieldEntity modelMetadataFieldEntity = metadataFieldEntitiereal.get(i);
                    createview.append(" JSON_VALUE(jsondata,'$."+modelMetadataFieldEntity.getFieldCode()+"') ");
                    createview.append(modelMetadataFieldEntity.getFieldCode());
                    if(i<metadataFieldEntitiereal.size()-1){
                        createview.append(",").append("\r\n");
                    }
                }
                createview.append(" from ").append(metadataTableEntity.getCode()).append(" with(nolock) ");
    
                dlBaseJdbcTemplate.update(updatetablesql.toString());
                dlBaseJdbcTemplate.update(dropviewSql.toString());
                dlBaseJdbcTemplate.update(createview.toString());
            }
        }catch (Exception ex){
            log.error("【执行"+this.getClass().getName()+".dbSyncInter() 方法失败 】异常："+ex.getMessage(),ex);
        }
    }
}
